﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WF_ExportTool.Common;
using WF_ExportTool.Configuration;
using WF_ExportTool.Configuration.Auto;
using WF_ExportTool.Configuration.DataV;
using WF_ExportTool.Configuration.Form;
using WF_ExportTool.Configuration.Grid;
using WF_ExportTool.Configuration.Tab;
using WF_ExportTool.Configuration.Tree;
using static WF_ExportTool.Common.CommonEnum;

namespace WF_ExportTool
{
    public partial class FMexportTool : Form
    {
        #region  定义全局变量
        CommonEnum.KindSign sign = KindSign.Grid;
        CommonEngine commonEngine = new CommonEngine();
        #endregion
        public FMexportTool()
        {           
            InitializeComponent();

        }
        /// <summary>
        ///  查询按钮事件
        /// 点击查询展示所查询的列表信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_check_Click(object sender, EventArgs e)
        {
            this.listView1.Items.Clear();//每次点击事件后将ListView中的数据清空，重新显示           
            if (sign == KindSign.Grid)
            {
                #region 列表
                LogHelper.WriteLog("列表数据查询及绑定listView数据展示,开始执行！");
                try
                {
                    //设置列信息
                    this.listView1.Columns.Clear();
                    this.listView1.Columns.Add("选择", 50, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("列表编码", 150, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("列表名称", 300, HorizontalAlignment.Center);


                    string txtBoxValue = this.txtBox_Name.Text; string strWhere;
                    if (txtBoxValue.Trim() == "") strWhere = "1=1";
                    else strWhere = "GridTitle like '%" + txtBoxValue + "%' or GridCode  like '%" + txtBoxValue + "%'";
                    IList<Grid_Main> gridMainList = commonEngine.ReadGrid_MainForDbIns(strWhere);

                    if (gridMainList != null)
                    {
                        for (int i = 0; i < gridMainList.Count; i++)
                        {
                            Grid_Main gridMain = gridMainList[i];
                            ListViewItem additem = new ListViewItem();
                            additem.SubItems.Clear();
                            //additem.Text = gridMain.GridCode;
                            additem.SubItems.Add(gridMain.GridCode);
                            additem.SubItems.Add(gridMain.GridTitle);
                            this.listView1.Items.Add(additem);
                            listView1.CheckBoxes = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("列表数据查询及绑定listView数据展示,发生异常,异常信息为", ex);
                }
                #endregion
            }
            if (sign == KindSign.Form)
            {
                #region 表单
                LogHelper.WriteLog("表单数据查询及绑定listView数据展示,开始执行！");
                try
                {
                    //设置列信息
                    this.listView1.Columns.Clear();
                    this.listView1.Columns.Add("选择", 50, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("表单编码", 150, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("表单名称", 300, HorizontalAlignment.Center);

                    string txtBoxValue = this.txtBox_Name.Text; string strWhere;
                    if (txtBoxValue.Trim() == "") strWhere = "1=1";
                    else strWhere = "FormTitle like '%" + txtBoxValue + "%'  or FormCode   like '%" + txtBoxValue + "%' ";
                    IList<Form_Main> formMainList = commonEngine.ReadForm_MainForDbIns( strWhere);

                    if (formMainList != null)
                    {
                        for (int i = 0; i < formMainList.Count; i++)
                        {
                            Form_Main gridMain = formMainList[i];
                            ListViewItem additem = new ListViewItem();
                            additem.SubItems.Clear();
                            //additem.Text = gridMain.GridCode;
                            additem.SubItems.Add(gridMain.FormCode);
                            additem.SubItems.Add(gridMain.FormTitle);
                            this.listView1.Items.Add(additem);
                            listView1.CheckBoxes = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("表单数据查询及绑定listView数据展示,发生异常,异常信息为", ex);
                }
                #endregion

            }
            if (sign == KindSign.Auto)
            {
                #region 自动编号
                LogHelper.WriteLog("自动编号数据查询及绑定listView数据展示,开始执行！");
                try
                {
                    //设置列信息
                    this.listView1.Columns.Clear();
                    this.listView1.Columns.Add("选择", 50, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("编码Code", 150, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("编号名称", 300, HorizontalAlignment.Center);

                    string txtBoxValue = this.txtBox_Name.Text; string strWhere;
                    if (txtBoxValue.Trim() == "") strWhere = "1=1";
                    else strWhere = "AutoName like '%" + txtBoxValue + "%'  or AutoCode like '%" + txtBoxValue + "%'";
                    IList<CP_AutoNum> autoMainList = commonEngine.ReadAuto_MainForDbIns( strWhere);

                    if (autoMainList != null)
                    {
                        for (int i = 0; i < autoMainList.Count; i++)
                        {
                            CP_AutoNum autoMain = autoMainList[i];
                            ListViewItem additem = new ListViewItem();
                            additem.SubItems.Clear();
                            //additem.Text = gridMain.GridCode;
                            additem.SubItems.Add(autoMain.AutoCode);
                            additem.SubItems.Add(autoMain.AutoName);
                            this.listView1.Items.Add(additem);
                            listView1.CheckBoxes = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("自动编号数据查询及绑定listView数据展示,发生异常,异常信息为", ex);
                }
                #endregion

            }
            if (sign == KindSign.Tab)
            {
                #region 标签页
                LogHelper.WriteLog("标签页数据查询及绑定listView数据展示,开始执行！");
                try
                {
                    //设置列信息
                    this.listView1.Columns.Clear();
                    this.listView1.Columns.Add("选择", 50, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("页签编号", 150, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("页面名称", 300, HorizontalAlignment.Center);

                    string txtBoxValue = this.txtBox_Name.Text; string strWhere;
                    if (txtBoxValue.Trim() == "") strWhere = "1=1";
                    else strWhere = "TabTitle like '%" + txtBoxValue + "%'  or TabCode  like '%" + txtBoxValue + "%'";
                    IList<Tab_Main> tabMainList = commonEngine.ReadTab_MainForDbIns(strWhere);

                    if (tabMainList != null)
                    {
                        for (int i = 0; i < tabMainList.Count; i++)
                        {
                            Tab_Main autoMain = tabMainList[i];
                            ListViewItem additem = new ListViewItem();
                            additem.SubItems.Clear();
                            //additem.Text = gridMain.GridCode;
                            additem.SubItems.Add(autoMain.TabCode);
                            additem.SubItems.Add(autoMain.TabTitle);
                            this.listView1.Items.Add(additem);
                            listView1.CheckBoxes = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("标签页数据查询及绑定listView数据展示,发生异常,异常信息为", ex);
                }
                #endregion

            }
            if (sign == KindSign.Tree)
            {
                #region 树工具
                LogHelper.WriteLog("树工具数据查询及绑定listView数据展示,开始执行！");
                try
                {
                    //设置列信息
                    this.listView1.Columns.Clear();
                    this.listView1.Columns.Add("选择", 50, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("树编号", 150, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("标题", 300, HorizontalAlignment.Center);

                    string txtBoxValue = this.txtBox_Name.Text; string strWhere;
                    if (txtBoxValue.Trim() == "") strWhere = "1=1";  
                    else strWhere = "TreeTitle like '%" + txtBoxValue + "%' or  TreeCode   like '%" + txtBoxValue + "%'";
                    IList<Tree_Main> treeMainList = commonEngine.ReadTree_MainForDbIns(strWhere);

                    if (treeMainList != null)
                    {
                        for (int i = 0; i < treeMainList.Count; i++)
                        {
                            Tree_Main autoMain = treeMainList[i];
                            ListViewItem additem = new ListViewItem();
                            additem.SubItems.Clear();
                            //additem.Text = gridMain.GridCode;
                            additem.SubItems.Add(autoMain.TreeCode);
                            additem.SubItems.Add(autoMain.TreeTitle);
                            this.listView1.Items.Add(additem);
                            listView1.CheckBoxes = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("树工具数据查询及绑定listView数据展示,发生异常,异常信息为", ex);
                }
                #endregion

            }
            if (sign == KindSign.DataV)
            {
                #region 图表
                LogHelper.WriteLog("数据统计（图表）数据查询及绑定listView数据展示,开始执行！");
                try
                {
                    //设置列信息
                    this.listView1.Columns.Clear();
                    this.listView1.Columns.Add("选择", 50, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("树编号", 150, HorizontalAlignment.Center);
                    this.listView1.Columns.Add("标题", 300, HorizontalAlignment.Center);

                    string txtBoxValue = this.txtBox_Name.Text; string strWhere;
                    if (txtBoxValue.Trim() == "") strWhere = "1=1";
                    else strWhere = "DataVTitle like '%" + txtBoxValue + "%' or DataVCode like '%" + txtBoxValue + "%'";
                    IList<DataV_Main> dataVMainList = commonEngine.ReadDataV_MainForDbIns(strWhere);

                    if (dataVMainList != null)
                    {
                        for (int i = 0; i < dataVMainList.Count; i++)
                        {
                            DataV_Main autoMain = dataVMainList[i];
                            ListViewItem additem = new ListViewItem();
                            additem.SubItems.Clear();
                            //additem.Text = gridMain.GridCode;
                            additem.SubItems.Add(autoMain.DataVCode);
                            additem.SubItems.Add(autoMain.DataVTitle);
                            this.listView1.Items.Add(additem);
                            listView1.CheckBoxes = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("数据统计（图表）数据查询及绑定listView数据展示,发生异常,异常信息为", ex);
                }
                #endregion

            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("导出所选择的数据,开始执行");
                int k = 0;
                int m = listView1.CheckedItems.Count;
                if (m == 0) { MessageBox.Show("请选择需要导出的数据"); return; }
                string[] a = new string[m];
                Queue<string> Q = new Queue<string>();
                for (int i = 0; i < m; i++)
                    if (listView1.CheckedItems[i].Checked)
                        Q.Enqueue(listView1.CheckedItems[i].SubItems[1].Text);
                while (Q.Count > 0)
                {
                    a[k] = Q.Dequeue();
                    k++;
                }
                IList<Dictionary<string, string>> exportContent = null; //= gridEngine.ExportGridData(a);

                if (sign == KindSign.Form)
                    exportContent = commonEngine.ExportData(a, "Form");
                if (sign == KindSign.Grid)
                    exportContent = commonEngine.ExportData(a, "Grid");
                if (sign == KindSign.Tab)
                    exportContent = commonEngine.ExportData(a, "Tab");
                if (sign == KindSign.Tree)
                    exportContent = commonEngine.ExportData(a, "Tree");
                if (sign == KindSign.DataV)
                    exportContent = commonEngine.ExportData(a, "DataV");
                if (sign == KindSign.Auto)
                    exportContent = commonEngine.ExportData(a, "Auto");


                this.DownLoadFile(exportContent);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("导出所选择的数据,发生异常,异常信息为", ex);
            }
        }

        //导出sql文件，提示本地保存
        private void DownLoadFile(IList<Dictionary<string, string>> exportContent)
        {
            foreach (Dictionary<string, string> diccontent in exportContent)
            {
                string filename = diccontent["name"];
                string content = diccontent["content"];
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "文本文件(*.sql)|*.sql|所有文件|*.*";//设置文件类型
                sfd.FileName = filename+ DateTime.Now.ToString("yyyyMMddHHmmss")   ;//设置默认文件名
                sfd.AddExtension = true;//设置自动在文件名中添加扩展名
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter sw = new StreamWriter(sfd.FileName,false,Encoding.GetEncoding("gb2312")))
                    {
                        sw.Write(content);
                    }
                }
            }
            MessageBox.Show("保存成功！");
               

        }

        private void button1_Click(object sender, EventArgs e)
        { 
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            //sfd.Filter = "数据库备份文件（*.bak）|*.bak|数据文件（*.mdf）|*.mdf|日志文件（*.ldf）|*.ldf";
            sfd.Filter = "数据库文件（*.sql）|*.sql";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;

            //设置默认的文件名(本人测试没成功)
            sfd.FileName = "YourFileName";// in wpf is  sfd.FileName = "YourFileName";
                                                 //点了保存按钮进入 
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string localFilePath = sfd.FileName.ToString(); //获得文件路径 
                string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名，不带路径
                string filePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));//获取文件路径，不带文件名
                                                                                              //给文件名前加上时间
                                                                                              //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
                                                                                              //在文件名里加字符
                                                                                              //saveFileDialog1.FileName.Insert(1,"dameng");   
                System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();//输出文件
                                                                                           //fs输出带文字或图片的文件，就看需求了
            }


        }

 
        /// <summary>
        /// 列表菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Columns.Clear();//清除列表数据源
            this.listToolStripMenuItem.BackColor = Color.PowderBlue;
            foreach (System.Windows.Forms.ToolStripMenuItem menuItem in menuStrip1.Items)
            {
                if (menuItem.Name == ((System.Windows.Forms.ToolStripMenuItem)sender).Name) continue;
                menuItem.BackColor = Control.DefaultBackColor;
            }
            sign = KindSign.Grid;
            this.label1.Text = "列表编号名称：";
        }

        /// <summary>
        /// 表单菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void formToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Columns.Clear();//清除列表数据源
            this.formToolStripMenuItem.BackColor = Color.PowderBlue;
            foreach (System.Windows.Forms.ToolStripMenuItem menuItem in menuStrip1.Items)
            {
                if (menuItem.Name == ((System.Windows.Forms.ToolStripMenuItem)sender).Name) continue;
                menuItem.BackColor = Control.DefaultBackColor;
            }
            sign = KindSign.Form;
            this.label1.Text = "表单编号名称：";
        }
        /// <summary>
        /// 标签页菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Columns.Clear();//清除列表数据源
            this.tabToolStripMenuItem.BackColor = Color.PowderBlue;
            foreach (System.Windows.Forms.ToolStripMenuItem menuItem in menuStrip1.Items)
            {
                if (menuItem.Name == ((System.Windows.Forms.ToolStripMenuItem)sender).Name) continue;
                menuItem.BackColor = Control.DefaultBackColor;
            }
            sign = KindSign.Tab;
            this.label1.Text = "标签页编号名称：";
        }
        /// <summary>
        /// 树工具菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Columns.Clear();//清除列表数据源
            this.treeToolStripMenuItem.BackColor = Color.PowderBlue;
            foreach (System.Windows.Forms.ToolStripMenuItem menuItem in menuStrip1.Items)
            {
                if (menuItem.Name == ((System.Windows.Forms.ToolStripMenuItem)sender).Name) continue;
                menuItem.BackColor = Control.DefaultBackColor;
            }
            sign = KindSign.Tree;
            this.label1.Text = "树工具编号名称：";
        }
        /// <summary>
        /// 数据统计菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Columns.Clear();//清除列表数据源
            this.dataVToolStripMenuItem.BackColor = Color.PowderBlue;
            foreach (System.Windows.Forms.ToolStripMenuItem menuItem in menuStrip1.Items)
            {
                if (menuItem.Name == ((System.Windows.Forms.ToolStripMenuItem)sender).Name) continue;
                menuItem.BackColor = Control.DefaultBackColor;
            }
            sign = KindSign.DataV;
            this.label1.Text = "统计编号名称：";
        }
        /// <summary>
        /// 自动编码工具点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Columns.Clear();//清除列表数据源
            this.autoToolStripMenuItem.BackColor = Color.PowderBlue;
            foreach (System.Windows.Forms.ToolStripMenuItem menuItem in menuStrip1.Items)
            {
                if (menuItem.Name == ((System.Windows.Forms.ToolStripMenuItem)sender).Name) continue;
                menuItem.BackColor = Control.DefaultBackColor;
            }
            sign = KindSign.Auto;
            this.label1.Text = "自动编码名称：";
        }
    }
}
